package com.xiguanlezz.cn.client;

import com.xiguanlezz.cn.client.codec.*;
import com.xiguanlezz.cn.common.RequestMessage;
import com.xiguanlezz.cn.common.ResponseMessage;
import com.xiguanlezz.cn.order.OrderOperation;
import com.xiguanlezz.cn.util.IdGenerateUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.concurrent.ExecutionException;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/10/17 14:27
 * @Description：客户端启动类
 */
public class Client {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture channelFuture = bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        pipeline.addLast(new OrderFrameDecoder());
                        pipeline.addLast(new OrderProtocolDecoder());
                        pipeline.addLast(new OrderResponsePrintHandler());
                        pipeline.addLast(new OrderFrameEncoder());
                        pipeline.addLast(new OrderProtocolEncoder());
                    }
                })
                .connect("127.0.0.1", 8888).sync();

        RequestMessage requestMessage = new RequestMessage(IdGenerateUtil.nextId(), new OrderOperation("白灼大虾", "上汤娃娃菜"));
        channelFuture.channel().writeAndFlush(requestMessage);
        channelFuture.channel().closeFuture().get();
    }
}
